package com.xcdh.auth.util;


import cn.hutool.json.JSONUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.xcdh.auth.consts.StringConst;


import java.util.Calendar;

public class JwtUtil {



    public static String createToken(Object user) {
        // 帐号加JWT私钥加密
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DATE, 7);
        Algorithm algorithm = Algorithm.HMAC256(StringConst.TOKEN_HMAC256_KEY);
        JWTCreator.Builder builder = JWT.create();
        // 附带account帐号信息
        builder.withClaim(StringConst.USER_KEY, JSONUtil.toJsonStr(user));
        return builder.withExpiresAt(instance.getTime())
                .sign(algorithm);
    }


    public static void verify(String token) {
        // 帐号加JWT私钥解密
        Algorithm algorithm = null;
        algorithm = Algorithm.HMAC256(StringConst.TOKEN_HMAC256_KEY);
        JWTVerifier verifier = JWT.require(algorithm).build();
        verifier.verify(token);
    }

    public static String parseToken(String token) {
        return JWT.decode(token).getClaim(StringConst.USER_KEY).asString();
    }

}
